package logic

import (
	"context"
	"encoding/json"
	"rent-ease/models/cache"
	"rent-ease/models/mysql"
	"time"

	"rent-ease/rentrpc/internal/svc"
	"rent-ease/rentrpc/rentrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *rentrpc.ListRequest) (*rentrpc.ListResponse, error) {
	// todo: add your logic here and delete this line

	var list []*rentrpc.List
	key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cacheData == "" {
		list = mysql.List(mysql.DB)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Minute*30)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	return &rentrpc.ListResponse{
		List: list,
	}, nil
}
